<template>
  <div class="terminal-view">
    <div class="terminal-header">
      <h2 class="page-title">命令行工具</h2>
      
      <!-- 会话管理 -->
      <div class="session-controls">
        <a-dropdown v-if="sessions.length > 0">
          <a-button type="primary" ghost>
            会话列表
            <DownOutlined />
          </a-button>
          <template #overlay>
            <a-menu @click="switchSession">
              <a-menu-item v-for="session in sessions" :key="session.id">
                {{ session.name }}
                <span class="session-time">{{ formatTime(session.lastActivity) }}</span>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        
        <a-button type="primary" @click="createNewSession">
          <PlusOutlined /> 新会话
        </a-button>
      </div>
    </div>
    
    <!-- 终端区域 -->
    <div class="terminal-container">
      <Terminal 
        v-if="activeSessionId" 
        ref="terminalRef"
        :session-id="activeSessionId"
        @close="handleTerminalClose"
        @error="handleTerminalError"
        @connected="handleTerminalConnected"
        @disconnected="handleTerminalDisconnected"
        @session-created="handleSessionCreated"
      />
      
      <div v-else class="terminal-placeholder">
        <a-empty description="没有活跃的终端会话">
          <template #extra>
            <a-button type="primary" @click="createNewSession">创建新会话</a-button>
          </template>
        </a-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { message } from 'ant-design-vue';
import { DownOutlined, PlusOutlined } from '@ant-design/icons-vue';
import Terminal from '@/components/Terminal/index.vue';
import instance from '@/api';

// 会话管理
const sessions = ref([]);
const activeSessionId = ref(null);
const terminalRef = ref(null);

// 获取会话列表
const fetchSessions = async () => {
  try {
    const response = await instance.get('/terminal/sessions');
    sessions.value = response.data.sessions || [];
    
    // 如果有会话但没有活跃会话，则激活第一个
    if (sessions.value.length > 0 && !activeSessionId.value) {
      activeSessionId.value = sessions.value[0].id;
    }
  } catch (error) {
    console.error('获取会话列表失败:', error);
    message.error('获取会话列表失败');
  }
};

// 创建新会话
const createNewSession = async () => {
  try {
    // 获取窗口大小
    const cols = 80;
    const rows = 24;
    
    const response = await instance.post('/terminal/sessions', { cols, rows });
    const { sessionId } = response.data;
    
    if (sessionId) {
      activeSessionId.value = sessionId;
      await fetchSessions();
    }
  } catch (error) {
    console.error('创建新会话失败:', error);
    message.error('创建新会话失败');
  }
};

// 切换会话
const switchSession = ({ key }) => {
  activeSessionId.value = key;
};

// 关闭会话
const closeSession = async (sessionId) => {
  try {
    await instance.delete(`/terminal/sessions/${sessionId}`);
    
    // 如果关闭的是当前会话，则清空当前会话ID
    if (activeSessionId.value === sessionId) {
      activeSessionId.value = null;
    }
    
    // 刷新会话列表
    await fetchSessions();
    
    message.success('会话已关闭');
  } catch (error) {
    console.error('关闭会话失败:', error);
    message.error('关闭会话失败');
  }
};

// 处理终端关闭
const handleTerminalClose = (sessionId) => {
  closeSession(sessionId);
};

// 处理终端错误
const handleTerminalError = (error) => {
  console.error('终端错误:', error);
};

// 处理终端连接成功
const handleTerminalConnected = () => {
  console.log('终端已连接');
};

// 处理终端断开连接
const handleTerminalDisconnected = () => {
  console.log('终端已断开连接');
};

// 处理会话创建
const handleSessionCreated = (sessionId) => {
  fetchSessions();
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  
  const date = new Date(timestamp * 1000);
  const now = new Date();
  
  // 如果是今天，只显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }
  
  // 否则显示日期和时间
  return date.toLocaleString([], { 
    month: 'numeric', 
    day: 'numeric', 
    hour: '2-digit', 
    minute: '2-digit' 
  });
};

// 生命周期钩子
onMounted(async () => {
  try {
    // 先获取会话列表
    await fetchSessions();
    
    // 如果没有会话，创建一个新会话
    if (sessions.value.length === 0) {
      console.log('没有现有会话，创建新会话...');
      await createNewSession();
    } else {
      console.log('找到现有会话:', sessions.value);
      activeSessionId.value = sessions.value[0].id;
    }
  } catch (error) {
    console.error('初始化终端失败:', error);
    message.error('初始化终端失败，请刷新页面重试');
  }
});

onUnmounted(() => {
  // 可以选择在页面卸载时关闭会话，也可以保持会话活跃
  // 这里选择保持会话活跃，以便用户可以返回时继续使用
});
</script>

<style scoped>
.terminal-view {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.terminal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.session-controls {
  display: flex;
  gap: 10px;
}

.terminal-container {
  flex: 1;
  border-radius: 4px;
  overflow: hidden;
  background-color: #000;
  min-height: 400px;
}

.terminal-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #f0f2f5;
}

.session-time {
  margin-left: 10px;
  font-size: 12px;
  color: #999;
}
</style> 